<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-row>
        <el-col class="cat_opt">
          <span>选择商品分类:</span>
          <!-- 级联选择器 -->
          <!-- options指定数据源 -->
          <el-cascader
            @change="handleChange"
            v-model="selectedKeys"
            clearable
            :options="cateList"
            :props="{
              expandTrigger: 'hover',
              label: 'cat_name',
              value: 'cat_id',
              children: 'children',
            }"
          >
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            :disabled="isBthDisabled"
            @click="addDialogVisible = true"
            >添加参数
          </el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTabData" border script>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteTag(index, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 编辑按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑
                </el-button>
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button
            type="primary"
            :disabled="isBthDisabled"
            @click="addDialogVisible = true"
            >添加属性
          </el-button>
          <el-table :data="onlyTabData" border script>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteTag(index, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 编辑按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑
                </el-button>
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form ref="editFormRef" :model="editForm" :rules="addFormRules">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 动态参数表格数据
      manyTabData: [],
      // 静态属性表格数据
      onlyTabData: [],
      // 级联选择框双向绑定数据
      selectedKeys: [],
      // 被激活的标签页名称
      activeName: 'many',
      // 添加参数对话框开关
      addDialogVisible: false,
      // 添加参数表单双向绑定对象
      addForm: {
        attr_name: ''
      },
      // 添加参数表单验证对象
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 编辑参数对话框开关
      editDialogVisible: false,
      // 编辑参数表单双向绑定对象
      editForm: {}
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败！')
      }
      this.cateList = res.data
      console.log(this.cateList)
      this.$message.success('获取商品分类列表成功！')
    },
    // 监听级联选择器
    handleChange () {
      this.getParamsData()
    },
    // 切换标签页事件
    handleClick () {
      this.getParamsData()
      console.log(this.activeName)
    },
    // 获取表格数据
    async getParamsData () {
      // 判断是否是第三级分类
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTabData = []
        this.onlyTabData = []
        return
      }
      const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes', {
        params: { sel: this.activeName }
      })
      console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('获取分类参数失败！') }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 添加属性用于控制文本框开关
        item.inputVisible = false
        // 添加属性储存文本框输入内容
        item.inputValue = ''
      })
      console.log(res)
      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    // 确定添加参数
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) { return this.$message.error('表单校验未通过') }
        const { data: res } = await this.$http.post(
          'categories/' + this.cateId + '/attributes', { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        console.log(res)
        if (res.meta.status !== 201) { return this.$message.error('添加参数失败') }
        // 关闭弹窗
        this.addDialogVisible = false
        // 刷新数据
        this.getParamsData()
        this.$message.success('添加参数成功！')
      })
    },
    // 监听添加参数对话框关闭事件，重置表单。
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 显示编辑对话框
    async showEditDialog (row) {
      // 查询当前参数信息
      const { data: res } = await this.$http.get(
        'categories/' + row.cat_id +
        '/attributes/' + row.attr_id,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('查询参数失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
      console.log(row, res)
    },
    // 确认编辑参数
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) { return this.$message.error('表单校验未通过') }
        const { data: res } = await this.$http.put('categories/' +
          this.editForm.cat_id + '/attributes/' +
          this.editForm.attr_id, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.editForm.attr_sel
        })
        console.log(res)
        if (res.meta.status !== 200) { return this.$message.error('编辑参数失败') }
        // 刷新表格数据
        this.getParamsData()
        this.editDialogVisible = false
        this.$message.success('编辑参数成功！')
      })
    },
    // 监听编辑参数对话框关闭事件，重置表单。
    editDialogClose () {
      this.editForm = {}
      this.$refs.editFormRef.resetFields()
    },
    // 确认删除参数
    async deleteParams (row) {
      // 弹框提示是否删除
      const confirmResult = await this.$confirm('此操作将删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      console.log(row)
      // 发起删除请求
      const { data: res } = await this.$http.delete(
        'categories/' + row.cat_id +
        '/attributes/' + row.attr_id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      // 刷新表格数据
      this.getParamsData()
      this.$message.success('删除成功')
    },
    // 显示添加标签文本框
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获得焦点。$nextTick作用：当页面重新渲染后再触发回调函数
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 文本框失去焦点或按下enter触发 关闭标签文本框
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 输入内容合法，压入对象的attr_vals数组
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求
      this.editTag(row)
    },
    // 删除Tag
    deleteTag (index, row) {
      row.attr_vals.splice(index, 1)
      console.log(row.attr_vals)
    },
    // 发起修改tag网络请求
    async editTag (row) {
      const { data: res } = await this.$http.put('categories/' + this.cateId + '/attributes/' + row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败！')
      }
      this.$message.success('修改参数项成功！')
    }
  },
  computed: {
    // 判断是否需要禁用按钮
    isBthDisabled () {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类id
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // 动态计算标题文本
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style scoped>
.cat_opt {
  margin: 15px 0;
}
.el-cascader {
  width: 30%;
  margin: 0 15px;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 150px;
}
</style>
